import React, { useState } from "react";
import { MenuFoldOutlined, MenuUnfoldOutlined } from "@ant-design/icons";
import { Layout, Menu, Button, theme } from "antd";
import { Route, Switch, useHistory } from "react-router-dom";
import { getCurrentMenus,getIdByKey,getCRUD } from "@/grant/Menu";
import { gettCurrentRoutes } from "@/grant/routes";

const { Header, Sider, Content } = Layout;

const currentMenus = getCurrentMenus();

const App: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false);
  const {
    token: { colorBgContainer },
  } = theme.useToken();

  const history = useHistory();

  const goPage: any = function (obj: any) {
    console.log("goPage.obj", obj);

    // 1、根据路径找到id。
    const id = getIdByKey(currentMenus,obj.key);
    console.log("找到的id:", id);

    // 2、根据id（如：0-1-0）获取当前组件的CRUD
    const crud = getCRUD(id);

    // 2、把id传给组件。
    history.push({ pathname: obj.key, state: { crud } }); //跳转页面时，传入当前路由的key或者CRUD;
  };

  return (
    <Layout>
      <Sider trigger={null} collapsible collapsed={collapsed}>
        <div className="demo-logo-vertical" />
        <Menu
          theme="dark"
          mode="inline"
          defaultSelectedKeys={["1"]}
          items={currentMenus}
          onClick={goPage}
        />
      </Sider>
      <Layout>
        <Header style={{ padding: 0, background: colorBgContainer }}>
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
            style={{
              fontSize: "16px",
              width: 64,
              height: 64,
            }}
          />
        </Header>
        <Content
          style={{
            margin: "24px 16px",
            padding: 24,
            minHeight: 280,
            background: colorBgContainer,
          }}
        >
          {/* switch是排他性匹配：既就是，当匹配上一个path后，不再继续匹配了 */}
          <Switch>
            {gettCurrentRoutes().map((item) => (
              <Route {...item} />
            ))}
          </Switch>
        </Content>
      </Layout>
    </Layout>
  );
};

export default App;
